<?php
class Credis{
	var $obj=null;

	function __construct($config=[]) {
		foreach ($config as $key => $value) {
			$this->$key=$value;
		}
	}

	function init() {
		switch ($this->type) {
			case 'sentinel':
				$redis = new redis();
				$redis->connect($this->host,$this->port);//连接sentinel服务
				$result = $redis->rawCommand('SENTINEL', 'masters');//返回master地址，其中第三个是host，第五个是port。完整内容可以打印出来
				if (count($result)==0) throw new MyException('服务器挂了……',MyException::THIRD);
				$this->host=$result[0][3];
				$this->port=$result[0][5];
			case 'normal':
				$this->obj = new redis();
				$succ=$this->obj->pconnect($this->host,$this->port);
				if (!$succ) throw new MyException('服务器挂了……',MyException::THIRD);
				$this->obj->auth($this->pass);
				$this->obj->select($this->db);
				break;
			case 'cluster':
				$redis = new RedisCluster(NULL, $this->host,2,2,true,empty($this->pass)?null:$this->pass);
				// In the event we can't reach a master, and it has slaves, failover for read commands
				$redis->setOption(RedisCluster::OPT_SLAVE_FAILOVER, RedisCluster::FAILOVER_ERROR);
				$this->obj=$redis;
				break;
			default:
				throw new MyException('服务暂不可用',MyException::THIRD);
				break;
		}
	}
	
	function __call($name,$param) {
		if ($this->obj==null) $this->init();
		if (($name=='set'||$name=='lPush')&&is_array($param[1]))
			$param[1]=json_encode($param[1]);
		$res=call_user_func_array([$this->obj,$name],$param);
		return ($name=='get'&&count($param)==1)?json_decode($res,true):$res;
	}
}
